<script setup lang='ts'>
import { useGetDescList, useGetHelpMenu, useGetHelpTab, useHelpDescAdd, useHelpDescDel, useHelpDescEdit, useHelpMenuAdd, useHelpMenuDel, useHelpMenuEdit } from '@fl/api/man-api/help-admin'
import { SearchForm, SearchTable } from '@fl/components'
import ButtonItem from '@fl/components/button-item.vue'
import FlUpload from '@fl/components/fl-upload.vue'
import { useMessage } from '@fl/hooks/web/use-message'
import { Editor } from '@fl/origin-components/Editor/index'
import { cloneDeep } from 'lodash-es'
import { ref, watch } from 'vue'

import { btns, defaultProps, initAddMenu, initDesc, initPage, initialState } from './constant'

const { createConfirmModal, createMessage } = useMessage()

const addDiglog = ref(false)
const descDiglog = ref(false)
const filterText = ref('')
const treeRef = ref<any>()
const tableData = ref<any>([])

const isClick = ref(false)
// 新增类目表单
const addForm = ref<any>(cloneDeep(initAddMenu))
const tablePage = ref<any>(cloneDeep(initPage))
const state = ref<any>(cloneDeep(initialState))
const descForm = ref<any>(cloneDeep(initDesc))

const gridOptions = reactive<any>({
    columns: [
        { field: 'title', title: '标题' },
        { field: 'type', title: '类型' },
        { field: 'createTime', title: '创建时间' },
        { slots: { default: 'operate' }, title: '操作', width: 250 },
    ],
    toolbarConfig: {
        slots: {
            buttons: 'toolbar_buttons',
        },
    },
})

const activeTab = ref('')

// 当前选中目录id
const menuId = ref('')

// 当前选中目录父级id
const parentId = ref('')

// 查询tab
const { data: tabsList } = useGetHelpTab()

const params = computed(() => ({
    ...state.value,
    catalogId: menuId.value,
    page: tablePage.value.currentPage,
    size: tablePage.value.pageSize,
    type: activeTab.value,
}))
// 查询内容列表
const { data: descData, isLoading: descLoading, refetch: descRefetch } = useGetDescList(params)

const treeParams = computed(() => ({
    type: activeTab.value,
}))
// 查询类目 树形数据
const { data: treeData, isLoading, refetch } = useGetHelpMenu(treeParams)

// 列表查询条件
const columns = [
    {
        colProps: {
            span: 8,
        },
        label: '关键字',
        prop: 'title',
    },
]

const rules = {
    catalogId: [{ message: '请选择目录', required: true, trigger: 'blur' }],
    content: [{ message: '请输入内容', required: true, trigger: 'blur' }],
    name: [{ message: '请输入名称', required: true, trigger: 'blur' }],
    title: [{ message: '请输入标题', required: true, trigger: 'blur' }],
}

// 新增类目表单配置
const addCol = computed(() => {
    const name = {
        fieldProps: {
            maxlength: 20,
            showWordLimit: true,
        },
        label: '名称',
        prop: 'name',
        // tooltip: '名称最多显示6个字符',
        valueType: 'copy',
    }
    const id = {
        label: '上级菜单',
        prop: 'parentId',
        valueType: 'select',
    }
    return isClick.value ? [name] : [name, id]
})

// 新增类目描述表单配置
const descCol: any = [
    {
        label: '标题',
        prop: 'title',
    },
    {
        label: '内容',
        prop: 'content',
    },
    {
        label: '选择目录',
        prop: 'catalogId',
    },
    {
        label: '附件',
        prop: 'attachment',
    },
]

function handleNodeClick(data: any) {
    menuId.value = data.id
    parentId.value = data.parentId

    tablePage.value = cloneDeep(initPage)

    descRefetch()
}

function getData(val: any) {
    tablePage.value.currentPage = 1
    state.value = {
        ...val,
    }

    descRefetch()
}

function tabChange() {
    // 重置目录
    filterText.value = ''
    menuId.value = ''

    state.value.title = ''

    // 重置列表
    tableData.value = []
}

function reset() {
    state.value = cloneDeep(initialState)
    tablePage.value = cloneDeep(initPage)

    filterText.value = ''

    // 重置tree选中样式
    treeRef.value.setCurrentKey(null)

    queryMenu()

    descRefetch()
}

// 删除富文本内容
const { mutate: mutateDescDel } = useHelpDescDel()

function doAction(item: any, row: any) {
    let attachment = []
    try {
        attachment = row.attachment ? JSON.parse(row.attachment) : []
    }
    catch (error) {
        console.error(error)
    }
    switch (item.value) {
        case 'copy':
            const { catalogId, content, title } = row
            descForm.value = {
                attachment,
                catalogId,
                content,
                title,
            }

            descDiglog.value = true
            break
        case 'edit':
            descDiglog.value = true

            descForm.value = {
                ...row,
                attachment,
            }
            break
        case 'delete':
            mutateDescDel(row.id, {
                onSuccess: () => {
                    descRefetch()
                    createMessage.success('操作成功')
                },
            })
            break
        default:
            break
    }
}

function doAdd() {
    descForm.value = cloneDeep(initDesc)

    // 新增内容 当前目录id
    descForm.value.catalogId = menuId.value

    descDiglog.value = true
}

// 目录新增 编辑保存
const { mutate: mutateAddMenu } = useHelpMenuAdd()
const { mutate: mutateEditMenu } = useHelpMenuEdit()
function saveMenu() {
    const params = {
        ...addForm.value,
        type: activeTab.value,
    }

    if (params?.id) {
        mutateEditMenu(params, {
            onSuccess: () => afterSave(),
        })
    }
    else {
        mutateAddMenu(params, {
            onSuccess: () => afterSave(),
        })
    }
}

// 富文本内容 新增 编辑保存接口
const { mutate: mutateAddDesc } = useHelpDescAdd()
const { mutate: mutateEditDesc } = useHelpDescEdit()
function saveDesc() {
    const attachment = descForm.value.attachment.length ? JSON.stringify(descForm.value.attachment) : ''

    const queryData = {
        ...descForm.value,
        attachment,
    }

    if (descForm.value?.id) {
        mutateEditDesc(queryData, {
            onSuccess: () => {
                descRefetch()
                descDiglog.value = false
                createMessage.success('操作成功')
            },
        })
    }
    else {
        mutateAddDesc(queryData, {
            onSuccess: () => {
                descRefetch()
                descDiglog.value = false
                createMessage.success('操作成功')
            },
        })
    }
}

function afterSave() {
    queryMenu()
    addDiglog.value = false
    createMessage.success('操作成功')
}

// 查询类目 清除缓存id
async function queryMenu() {
    await refetch()

    // 重置选中
    menuId.value = ''
    parentId.value = ''
}

function addMenu() {
    // 重置表单
    addForm.value = cloneDeep(initAddMenu)

    // 回显当前选中目录
    addForm.value.parentId = menuId.value

    addDiglog.value = true
    isClick.value = false
}

function doEditMenu(row: any) {
    addDiglog.value = true
    isClick.value = false
    const { id, name, parentId = '' } = row

    // 数据回显
    addForm.value = {
        id,
        name,
        parentId,
        type: activeTab.value,
    }
}

// 删除类目
const { mutate: mutateMenuDel } = useHelpMenuDel()
function doDelMenu(data: any) {
    if (data.catalogVOList.length) {
        createMessage.error('当前存在子目录，禁止删除')
        return
    }
    createConfirmModal({ content: '是否确认删除？', onError: () => {}, onSuccess: () => {
        mutateMenuDel(data.id, {
            onSuccess: () => {
                createMessage.success('操作成功')

                queryMenu()
            },
        })
    } })
}

function filterNode(value: string, data: any) {
    if (!value)
        return true
    return data.name.includes(value)
}

watch(filterText, (val) => {
    treeRef.value!.filter(val)
})

watchEffect(() => {
    if (descData.value) {
        tableData.value = descData.value?.records ?? []
        tablePage.value.total = descData.value.total ?? 0
    }

    if (tabsList.value && activeTab.value === '') {
        activeTab.value = tabsList.value[0].dictValue
        state.value.type = activeTab.value
    }
})
</script>

<template>
    <ElCard class="">
        <el-tabs v-model="activeTab"
                 @tab-change="tabChange"
        >
            <el-tab-pane v-for="item in tabsList"
                         :key="item.dictValue"
                         :label="item.dictLabel"
                         :name="item.dictValue"
            />
        </el-tabs>

        <div class="flex justify-between">
            <ElCard class="w-20%"
                    shadow="never"
            >
                <div flex>
                    <ElInput v-model="filterText" />

                    <ElButton class="el-button el-button--primary el-button--default ml-6"
                              @click="addMenu"
                    >
                        新建目录
                    </ElButton>
                </div>

                <el-tree ref="treeRef"
                         v-loading="isLoading"
                         :data="treeData"
                         class="py-10"
                         node-key="id"
                         highlight-current
                         default-expand-all
                         :props="defaultProps"
                         :expand-on-click-node="false"
                         :filter-node-method="filterNode"
                         @node-click="handleNodeClick"
                >
                    <template #default="{ node, data }">
                        <div class="flex w-full justify-between">
                            <el-tooltip :disabled="node.label.length < 8"
                                        effect="light"
                                        :content="node.label"
                                        placement="top"
                            >
                                <span class="text-ellipsis w-110 ws-nowrap of-hidden">{{ node.label }}</span>
                            </el-tooltip>

                            <span class="c-#DA0004">

                                <el-icon @click.stop="doEditMenu(data)">
                                    <EditPen />
                                </el-icon>

                                <el-icon class="ml-10"
                                         @click.stop="doDelMenu(data)"
                                >
                                    <Delete />
                                </el-icon>
                            </span>
                        </div>
                    </template>
                </el-tree>
            </ElCard>

            <ElCard class="ml-20 w-80%"
                    shadow="never"
            >
                <SearchForm v-bind="state"
                            :key="activeTab"
                            :columns="columns"
                            submit-text="查询"
                            class="mb-20"
                            @submit="getData"
                            @reset="reset"
                />

                <SearchTable v-bind="gridOptions"
                             v-model:pager="tablePage"
                             v-loading="descLoading"
                             :data="tableData"
                >
                    <template #toolbar_buttons>
                        <ElButton type="primary"
                                  @click="doAdd"
                        >
                            新增
                        </ElButton>
                    </template>

                    <template #operate="{ row }">
                        <ButtonItem :btns="btns"
                                    @btn-click="doAction($event, row)"
                        />
                    </template>
                </SearchTable>
            </ElCard>
        </div>
    </ElCard>
    <!-- 类目新增编辑弹框 -->
    <PlusDialogForm v-model:visible="addDiglog"
                    v-model="addForm"
                    :title="addForm?.id ? '编辑' : '新增'"
                    width="500"
                    :form="{ columns: addCol, rules }"
                    @confirm="saveMenu"
    >
        <template #plus-field-parentId>
            <el-cascader v-model="addForm.parentId"
                         class="w-full"
                         :disabled="addForm?.id"
                         :options="treeData"
                         :show-all-levels="false"
                         clearable
                         :props="{ expandTrigger: 'hover', label: 'name', value: 'id', children: 'catalogVOList', checkStrictly: true, emitPath: false }"
            />
        </template>
    </PlusDialogForm>
    <!-- 富文本新增编辑弹框 -->
    <PlusDialogForm :key="String(descDiglog)"
                    v-model:visible="descDiglog"
                    v-model="descForm"
                    :title="descForm?.id ? '编辑' : '新增'"
                    :form="{ columns: descCol, rules, labelWidth: 100 }"
                    @confirm="saveDesc"
    >
        <template #plus-field-content>
            <Editor v-model="descForm.content"
                    is-mall-admin
                    :height="300"
            />
        </template>

        <template #plus-field-catalogId>
            <el-cascader v-model="descForm.catalogId"
                         class="w-full"
                         :options="treeData"
                         :disabled="descForm?.id"
                         :show-all-levels="false"
                         clearable
                         :props="{ expandTrigger: 'hover', label: 'name', value: 'id', children: 'catalogVOList', checkStrictly: true, emitPath: false }"
            />
        </template>

        <template #plus-field-attachment>
            <FlUpload :key="String(descForm?.id) "
                      v-model="descForm.attachment"
                      is-mall-admin
                      list-type="text"
                      :limit="5"
                      :file-size="50"
                      accept=".docx,.pdf,.xlsx"
                      tips
            />
        </template>
    </PlusDialogForm>
</template>

<style lang="scss" scoped>
</style>
